package com.atguigu.config.websocket1;
import java.util.concurrent.CopyOnWriteArraySet;
import javax.websocket.Session;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.CloseStatus;
import org.springframework.web.socket.WebSocketHandler;
import org.springframework.web.socket.WebSocketMessage;
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.handler.TextWebSocketHandler;
/**
 * 	在组件里可以注入次组件,来发送消息
 * 	在此组件里可以注入其他组件,来完成其他工作
 * @author nrzt
 *
 */
//WebSocketHandler
@Component("myHandler")   
public class MyWebSocketHandler extends TextWebSocketHandler {
	//@Autowired
    //private UserLoginDao userLoginDao;
	
	
	//静态变量，用来记录当前在线连接数。应该把它设计成线程安全的。
    private static int onlineCount = 0;
    //concurrent包的线程安全Set，用来存放每个客户端对应的MyWebSocket对象。
    //private static CopyOnWriteArraySet<WebSocketServer> webSocketSet = new CopyOnWriteArraySet<WebSocketServer>();
    private static CopyOnWriteArraySet<WebSocketSession> sessionSet = new CopyOnWriteArraySet<WebSocketSession>();
    //与某个客户端的连接会话，需要通过它来给客户端发送数据
    private Session session;
    /**
     * 用户标识
     */
    private String userId;
    
    /**
     * 初次链接成功执行
     */
	@Override
	public void afterConnectionEstablished(WebSocketSession session) throws Exception {
		//session.getHandshakeHeaders().get("userId");
		this.userId = (String) session.getAttributes().get("userId");
		//userLoginDao.online(this.userId, 1);
		sessionSet.add(session);
		System.out.println("------afterConnectionEstablished-----------"+this.userId);
	}
	
	/**
	 * 连接关闭
	 */
	@Override
	public void afterConnectionClosed(WebSocketSession session, CloseStatus status) throws Exception {
		//userLoginDao.online(this.userId, 0);
		sessionSet.remove(session);
		System.out.println("------afterConnectionClosed-----------"+this.userId);
	}
	/**
	 * 消息处理器
	 */
	@Override
	public void handleMessage(WebSocketSession session, WebSocketMessage<?> message) throws Exception {
		System.out.println("-------handleMessage----------"+message.getPayload());
//		Map msg = JSONObject.parseObject(message, Map.class); 
//    	HttpSession httpSession= (HttpSession) session.getUserProperties().get(HttpSession.class.getName());
//    	UserPo user = (UserPo)httpSession.getAttribute("user");
//    	String mark = String.valueOf( msg.get("mark" ));
//    	if("admin_online".equals(mark)) {//管理员登录，通知所有已在线用户
//    		for (WebSocketServer ws : webSocketSet) {
//    			if(!(ws.userId.equals(user.getUserId()))) ws.session.getBasicRemote().sendText(JSONArray.toJSONString(msg));
//    		}
//    	}else if("teacher_online".equals(mark)) { //老师在线，通知管理员与学生
//    		UserLoginDao userLoginDao =  (UserLoginDao) ApplicationContextRegister.getApplicationContext().getBean(UserLoginDao.class);
//    		List<Map<String, Object>> students = userLoginDao.findAdminAndStudentByOrg(user.getOrgNo(),1);
//    		for (WebSocketServer ws : webSocketSet) {
//    			for (Map<String, Object> student : students) {
//					String studentId = String.valueOf(student.get("USER_ID"));
//					if(ws.userId.equals(studentId )) ws.session.getBasicRemote().sendText(JSONArray.toJSONString(msg));
//				}
//    		}
//    	}else if("student_online".equals(mark)) {//学生在线，通知老师和管理员
//    		UserLoginDao userLoginDao =  (UserLoginDao) ApplicationContextRegister.getApplicationContext().getBean(UserLoginDao.class);
//    		String currentUserOrgNo =  user.getOrgNo();
//    		for (WebSocketServer ws : webSocketSet) {
//    			List<Map<String, Object>> teacher = userLoginDao.findAdminAndTeacherByOrg(currentUserOrgNo, 1);
//    			for (Map<String, Object> map : teacher) {
//    				String teacherId = String.valueOf(map.get("USER_ID"));
//					if(ws.userId.equals(teacherId ))	ws.session.getBasicRemote().sendText(JSONArray.toJSONString(msg));	
//				}
//    		}
//    	}else if( "grant_exam".equals(mark) ) {//老师下发试卷给学生
//    		//{mark:"grant_exam", paperId:selectPaperId, studentIds:selectStudentIds}
//    		 List<String> studentIds= JSONArray.parseArray(String.valueOf( msg.get("studentIds") ), String.class);
//    		 msg.remove("studentIds");
//    		 for (WebSocketServer ws : webSocketSet) {
//    			 for (String studentId : studentIds) {
//    				 if(ws.userId.equals(studentId )){	
//    					 msg.put("teacherId", user.getUserId());
//    					 msg.put("studentId", studentId);
// 						ws.session.getBasicRemote().sendText(JSONArray.toJSONString(msg));
// 					}
//				}
//    		 }
//    		 
//    	}else if( "ready_exam".equals(mark) ) {//学生准备考试
//    		//{ mark:"ready_exam", teacherId:teacherId,paperId:paperId,examId:examId }
//    		String teacherId  = String.valueOf(msg.get("teacherId"));
//    		for (WebSocketServer ws : webSocketSet) {   			
//    			if(ws.userId.equals(teacherId)) {
//    				 msg.put("studentId", user.getUserId());
//    				ws.session.getBasicRemote().sendText(JSONArray.toJSONString(msg));
//    			}
//    		}
//    	}else if("strat_exam".equals(mark)) {//老师开启考试，即控制学生电脑发放试卷
//    		//{ mark:"strat_exam", studentIds:selectStudentIds, paperId:selectPaperId }
//    		List<String> studentIds= JSONArray.parseArray(String.valueOf( msg.get("studentIds") ), String.class);
//    		msg.remove("studentIds");
//    		for (WebSocketServer ws : webSocketSet) {
//    			for (String studentId : studentIds) {
//	   				if(ws.userId.equals(studentId )){		   					
//	   					msg.put("teacherId", user.getUserId());
//	   					msg.put("studentId", studentId);
//						ws.session.getBasicRemote().sendText(JSONArray.toJSONString(msg));
//					}
//				}
//    		}
//    	}else if("answer_exam".equals(mark)) {//老师开启考试，即控制学生电脑发放试卷
//    		//{ mark:"answer_exam", paperId:paperId, studentId:studentId,teacherId: teacherId,examId:paper.EXAM_ID}  
//    		String teacherId  = String.valueOf(msg.get("teacherId"));
//    		for (WebSocketServer ws : webSocketSet) {    			
//    			if(ws.userId.equals(teacherId)) {
//    				ws.session.getBasicRemote().sendText(JSONArray.toJSONString(msg));
//    			}
//    		}
//    	}else if("end_exam".equals(mark)) {//学生结束考试,老师接收
//    		//{ mark:"end_exam", examId:examId}
//    		ExamDao examDao =  (ExamDao) ApplicationContextRegister.getApplicationContext().getBean(ExamDao.class);
//    		String examId = String.valueOf(msg.get("examId"));
//    		examDao.updateExamStstus(examId, "3");   	
//    		List<Map<String, Object>> list =examDao.findExamById(examId);
//    		String teacherId = String.valueOf(list.get(0).get("TEACHER_ID"));
//    		for (WebSocketServer ws : webSocketSet) {    			
//    			if(ws.userId.equals(teacherId)) {
//    				msg.put("teacherId", teacherId);
//    				ws.session.getBasicRemote().sendText(JSONArray.toJSONString(msg));
//    			}
//    		}
//    	}
	}
	
	
	
	/**
	 * 发生错误
	 */
	@Override
	public void handleTransportError(WebSocketSession session, Throwable exception) throws Exception {
		
	}

	@Override
	public boolean supportsPartialMessages() {
		return false;
	}
	
	
   
}